#!/usr/bin/python
#coding:utf-8
'''
决策树模型
'''
from sklearn import tree
from sklearn import datasets
import pickle
import pydotplus
import pandas
from sklearn import model_selection
import numpy as np


def createTree(url):
	names=["utcstarttime","city_id","province_id","starttime","cell_id","VoLteAudErl","VoLteVidErl","VoLteAudOrigCallSuccNbr","VoLteAudTermCallSuccNbr","VoLteAudOrigCallNbr","VoLteAudTermCallNbr","VoLteAudSuccRate","VoLteAudNetCallNbr","VoLteAudNetSuccRate","VoLteVidOrigCallSuccNbr","VoLteVidTermCallSuccNbr","VoLteVidOrigCallNbr","VoLteVidTermCallNbr","VoLteVidSuccRate","VoLteVidNetCallNbr","VoLteVidNetSuccRate","VoLteAudOffLineNbr","VoLteAudOrigCallReplyNbr","VoLteAudTermCallReplyNbr","VoLteAudOffLineRate","VoLteVidOffLineNbr","VoLteVidOrigCallReplyNbr","VoLteVidTermCallReplyNbr","VoLteVidOffLineRate","VoLteOrigCallTimeVtoV","VoLteOrigCallTimeVtoAll","SRVCCSwitchSuccNbr","SRVCCSwitchAttNbr","SRVCCSwitchSuccRate","SRVCCSwitchTime","RTCPMos","RTPMosUl","RTPMosDl","RTPPktLossUl","VolteActiveUserNbr","class"]
	dataframe = pandas.read_csv(url,names=names)
	del names[-1]
	
	array = dataframe.values
	x=array[:,0:40]  
	y = array[:,40] 
	lab=list(set(y))#类别去重
	print lab

    #75%训练  25%测试
	X_train,X_test,y_train,y_test = model_selection.train_test_split(x,y,test_size=0.25)
    #创建决策树
	clf=tree.DecisionTreeClassifier() #默认Gini基尼不纯度 entropy 采用ID3算法criterion='entropy'
    #生成决策树
	clf = clf.fit(X_train, y_train)
	#输出每个特征的重要程度
	print "tezheng",clf.feature_importances_
	result=clf.score(X_test,y_test)
	print "Success",result

	#保存决策树
	# saveTree(clf)
    #加载决策树
	# clf=loadTree()
	# print clf.feature_importances_

	#结果预测
	# fen=clf.predict([[1517277600,27,270,201801301000,111160580,0.31,0.0,27,14,27,16,95.35,27,100.0,0,0,0,0,0.0,0,0.0,1,15,3,5.56,0,0,0,0.0,2674,6540,1,1,100.0,396,4.23,4.23,4.23,0.06,25]])
	# print "样本分类",fen
	class_Name=['zero','one','two','three','four','five','sex']
	#算法模型图生成png或pdf文件  feature_name 特征列表   class_names 标签列表
	# dot_data = tree.export_graphviz(clf, out_file=None) #不指定类别颜色
	dot_data = tree.export_graphviz(clf, out_file=None,feature_names= names,class_names=class_Name,filled=True, rounded=True,special_characters=True) 

	graph = pydotplus.graph_from_dot_data(dot_data) 
    #保存文件 
	graph.write_png("./work/src/algorithm/DecisionTree/sciki.png")

# 保存决策树
def saveTree(tree):
	filename='./work/src/algorithm/DecisionTree/tree-scikit.sav'
	pickle.dump(tree,open(filename,'wb'))

#加载决策树
def loadTree():	#加载模型
	filename='./work/src/algorithm/DecisionTree/tree-scikit.sav'
	load_model = pickle.load(open(filename,'rb'))
	return load_model

def main():
    url=".\work\data\ecicikit.txt";
    createTree(url)

if __name__ == '__main__':
    main()